package blue.jdbc.internal.core.engine;

import blue.jdbc.core.engine.QueryDao;
import blue.jdbc.core.parser.DaoConfig;
import blue.jdbc.internal.core.parser.DaoConfigCache;
import blue.jdbc.internal.core.parser.ParserFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Jin Zheng
 * @since 1.0 2021-12-21
 */
public class ComponentFactory {
	private static Logger logger = LoggerFactory.getLogger(ComponentFactory.class);

	private final DaoConfigCache daoConfigCache;
	private final DefaultJdbcOperation jdbcOperation;

	public ComponentFactory(ParserFactory parserFactory, DefaultJdbcOperation jdbcOperation) {
		this.daoConfigCache = parserFactory.getDaoConfigCache();
		this.jdbcOperation = jdbcOperation;
		this.initDao();
	}

	private void initDao() {
		var map = daoConfigCache.all();
		for (var entry : map.entrySet()) {
			var config = entry.getValue();
			if (config.getObject() instanceof QueryDao q) {
				q.setJdbcOperation(jdbcOperation);
				continue;
			}
			var bean = config.getJavaBean();
			var field = bean.getField(DaoConfig.FIELD_JDBC);
			if (field == null) {
				continue;
			}
			field.setFieldValue(config.getObject(), jdbcOperation);
		}
	}

	public <T> T getDao(Class<T> clazz) {
		var config = daoConfigCache.get(clazz);
		if (config == null) {
			return null;
		}
		return config.getObject();
	}

}
